/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package my12306;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import my12306.bean.Seats;
import my12306.table.KeyValueItem;

/**
 * 用于显示和编辑乘车人信息
 *
 * @author Jack
 */
public class PassengerInfoPanel extends javax.swing.JPanel {

    /**
     * it debug set to true, will print debug info.
     */
    private boolean DEBUG = false;
    /**
     * data model of PassengerInfoPanel
     */
    private PassengerInfoModel model;

    /**
     * Creates new form PassengerInfoPanel
     */
    public PassengerInfoPanel() {
        super(new GridLayout(1, 0));
        initComponents();
        init1();
    }

    /**
     * set data for PassengerInfoPanel. the data is in Vector<Vector<Object>>
     * format.
     *
     * @see PassengerInfoModel.columnNames for column structure
     * @param data
     */
    public void setData(List<List<Object>> data) {
        this.getModel().setData(data);
    }

    /**
     * add one row to data model. the data is in Vector<Object> format.
     *
     * @see PassengerInfoModel.columnNames for column structure
     * @param row
     */
    public void add(List<Object> row) {
        this.getModel().add(row);
    }

    /**
     * not used in this version
     *
     * @param data
     */
    public void appendData(List<List<Object>> data) {
        this.getModel().appendData(data);
    }

    /**
     * delete the selected row. PassengerInfoPanel is SINGLE_SELECTION
     */
    public void deleteSelected() {
        int row = table.getSelectedRow();
        row = table.convertRowIndexToModel(row);
        delete(row);
        table.updateUI();
    }

    /**
     * deleted the row specified by index.
     *
     * @param index the row index to deleted.
     */
    public void delete(int index) {
        if (index >= 0) {
            getModel().remove(index);
            table.updateUI();
        }
    }

    void init1() {
        model = new PassengerInfoModel();
        getTable().setModel(getModel());
        getTable().setPreferredScrollableViewportSize(new Dimension(500, 70));
        getTable().setFillsViewportHeight(true);


        TableColumn xibie = getTable().getColumnModel().getColumn(1);
        JComboBox xibieComboBox = new JComboBox();
        for (KeyValueItem item : Seats.allSeats().values()) {
            xibieComboBox.addItem(item);
        }
        xibieComboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                JComboBox comboBox = (JComboBox) e.getSource();
//                KeyValueItem item = (KeyValueItem) comboBox.getSelectedItem();
//                System.out.println(item.getKey() + " : " + item.getValue());
            }
        });
        xibieComboBox.setRenderer(new BasicComboBoxRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index,
                    boolean isSelected, boolean cellHasFocus) {
//                if (value instanceof KeyValueItem) {
//                    KeyValueItem entry = (KeyValueItem) value;
//                    return super.getListCellRendererComponent(list, entry.getKey(), index, isSelected, cellHasFocus);
//                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        xibie.setCellEditor(new DefaultCellEditor(xibieComboBox));


        TableColumn piaozhong = getTable().getColumnModel().getColumn(2);
        JComboBox piaozhongComboBox = new JComboBox();
        for (KeyValueItem item : KeyValueItem.tickets.values()) {
            piaozhongComboBox.addItem(item);
        }
        piaozhongComboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                JComboBox comboBox = (JComboBox) e.getSource();
//                KeyValueItem item = (KeyValueItem) comboBox.getSelectedItem();
//                System.out.println(item.getKey() + " : " + item.getValue());
            }
        });
        piaozhongComboBox.setRenderer(new BasicComboBoxRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index,
                    boolean isSelected, boolean cellHasFocus) {
//                if (value instanceof KeyValueItem) {
//                    KeyValueItem entry = (KeyValueItem) value;
//                    return super.getListCellRendererComponent(list, entry.getKey(), index, isSelected, cellHasFocus);
//                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        piaozhong.setCellEditor(new DefaultCellEditor(piaozhongComboBox));

        TableColumn idColumn = getTable().getColumnModel().getColumn(4);

        JComboBox idTypeComboBox = new JComboBox();
        for (KeyValueItem item : KeyValueItem.ids.values()) {
            idTypeComboBox.addItem(item);
        }
        idTypeComboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                JComboBox comboBox = (JComboBox) e.getSource();
//                KeyValueItem item = (KeyValueItem) comboBox.getSelectedItem();
//                System.out.println(item.getKey() + " : " + item.getValue());
            }
        });
        idTypeComboBox.setRenderer(new BasicComboBoxRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index,
                    boolean isSelected, boolean cellHasFocus) {
//                if (value instanceof KeyValueItem) {
//                    KeyValueItem entry = (KeyValueItem) value;
//                    return super.getListCellRendererComponent(list, entry.getKey(), index, isSelected, cellHasFocus);
//                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        idColumn.setCellEditor(new DefaultCellEditor(idTypeComboBox));


    }

    /**
     * @return the table
     */
    public javax.swing.JTable getTable() {
        return table;
    }

    /**
     * @return the model
     */
    public PassengerInfoModel getModel() {
        return model;
    }

    /**
     * the data model implement for PassengerInfoPanel
     */
    class PassengerInfoModel extends AbstractTableModel {

        /**
         * column structure
         */
        private String[] columnNames = {"序号", "席别", "票种", "姓名", "证件类型", "证件号码", "手机号"};
        /**
         * row data of the model.
         */
        private List<List<Object>> data;

        /**
         *
         */
        public PassengerInfoModel() {
            if (data == null) {
                data = new ArrayList<List<Object>>();
//                Vector<Object> row = new Vector<Object>();
//                row.add("1");
//                row.add(KeyValueItem.getSeatType("1"));
//                row.add(KeyValueItem.getTicketType("1"));
//                row.add("您的姓名");
//                row.add(KeyValueItem.getIDType("1"));
//                row.add("您的证件号码");
//                row.add("您的手机号码");
//                data.add(row);
            }
        }

        public void add(List<Object> row) {
            this.data.add(row);
            fireTableDataChanged();
        }

        /**
         * update seq column. to insure the seq is grow from 1.
         *
         */
        void updateIndex() {
            for (int i = 0; i < data.size(); i++) {
                List<Object> row = data.get(i);
                row.set(0, "" + (i + 1));
            }
        }

        /**
         * delete data
         *
         * @param index
         */
        public void remove(int index) {
            data.remove(index);
            updateIndex();
            fireTableDataChanged();
        }

        public int getColumnCount() {
            return getColumnNames().length;
        }

        public int getRowCount() {
            return data.size();
        }

        @Override
        public String getColumnName(int col) {
            return getColumnNames()[col];
        }

        public Object getValueAt(int row, int col) {
            return data.get(row).get(col);
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        @Override
        public Class getColumnClass(int col) {
            return getValueAt(0, col).getClass();
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        @Override
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col > 0) {
                return true;
            } else {
                return false;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        @Override
        public void setValueAt(Object value, int row, int col) {
            try {
                if (DEBUG) {
                    System.out.println("Setting value at " + row + "," + col
                            + " to " + value
                            + " (an instance of "
                            + value.getClass() + ")");
                }

                data.get(row).set(col, value);
                fireTableCellUpdated(row, col);

                if (DEBUG) {
                    System.out.println("New value of data:");
                    printDebugData();
                }
            } catch (Exception ex) {
                System.out.println(ex.toString());
            }
        }

        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i = 0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j = 0; j < numCols; j++) {
                    Object value = getValueAt(i, j);
                    if (value instanceof KeyValueItem) {
                        KeyValueItem item = (KeyValueItem) value;
                        System.out.print("  " + item.getKey() + "->" + item.getValue());
                    } else {
                        System.out.print("  " + value);
                    }
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }

        /**
         * @return the columnNames
         */
        public String[] getColumnNames() {
            return columnNames;
        }

        /**
         * @param columnNames the columnNames to set
         */
        public void setColumnNames(String[] columnNames) {
            this.columnNames = columnNames;
        }

        /**
         * @return the data
         */
        public List<List<Object>> getData() {
            return data;
        }

        /**
         * @param data the data to set
         */
        public void setData(List<List<Object>> data) {
            this.data = data;
            fireTableDataChanged();
        }

        /**
         * not used in this version
         *
         * @param data
         */
        public void appendData(List<List<Object>> data) {
            List<List<Object>> result = new ArrayList<List<Object>>();
            for (int i = 0; i < this.data.size(); i++) {
                List<Object> obj1 = this.data.get(i);
                for (int j = 0; j < data.size(); j++) {
                    List<Object> obj2 = data.get(j);
                    if (!obj1.get(3).equals(obj2.get(3))
                            && !obj1.get(5).equals(obj2.get(5))) {
                        result.add(obj2);
                    }
                }
            }
            this.data.addAll(result);
            updateIndex();
//            this.data = data;
            fireTableDataChanged();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        table.setFillsViewportHeight(true);
        table.setName("table"); // NOI18N
        jScrollPane1.setViewportView(table);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 533, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}
